<template>
	<div class="c-p-panel">
		<div class="form">
			<Form ref="form" :model="params" :rules="rules" :label-width="80">
				<Form-item label="广告标题" style="width: 500px;" prop="title">
					<Input v-model="params.title" placeholder="请输入广告标题" size="large"></Input>
				</Form-item>
				
				<Form-item label="广告类型" style="width: 300px;" prop="type">
					<Select v-model="params.type" size="large">
						<Option 
							v-for="(item, index) in initData.types" 
							:value="item.tid" 
							:key="index"
							v-text="item.value">
						</Option>
					</Select>
				</Form-item>
				
				<Form-item label="关联数据" style="width: 500px;" prop="webUrl" 
					v-if="params.type == 1 || params.type == 3">
					<Input v-model="params.webUrl" placeholder="请输入关联网页链接" size="large"></Input>
				</Form-item>
				
				<Form-item label="关联影人" style="width: 500px;" prop="userId" v-if="params.type == 2">
					<Select
		                v-model="params.userId"
		                filterable
		                remote
		                ref="userSelect"
		                :remote-method="searchUser"
		                :loading="isSearchUserLoading">
		                <Option v-for="(item, index) in users" 
		                		:value="item.uid" 
		                		:key="index"
		                		:label="item.name">
		                		<div>
		                			<CUserFilterItem :data="item">
								</CUserFilterItem>
		                		</div>
		                </Option>
		            </Select>
				</Form-item>
				
				<Form-item label="开始日期" prop="startTime">
					 <DatePicker type="date" 
					 	style="width: 230px;"
					 	v-model="params.startTime"
					 	placeholder="选择开始日期" 
					 	size="large">
					 </DatePicker>
				</Form-item>
				
				<Form-item label="结束日期" prop="endTime">
					<DatePicker type="date" 
						style="width: 230px;"
						v-model="params.endTime"
					 	placeholder="选择结束日期" 
					 	size="large">
					 </DatePicker>
				</Form-item>
	
				<Form-item label="发布状态" style="width: 300px;" prop="status">
					<Select v-model="params.status" size="large">
						<Option 
							v-for="(item, index) in initData.status" 
							:value="item.id" 
							:key="index"
							v-text="item.value">
						</Option>
					</Select>
				</Form-item>
				
				<Form-item label="图片" prop="img.url"
					:rules="{required: true, type: 'string', message: '广告图片不能为空', trigger: 'change'}">
					<CImagePicker
						:progress="imgProgress"
						:durl="params.img.url"
						:rate="params.img.rate"
						:display="params.img.display"
						@upload-data="uploadImg">
					</CImagePicker>
				</Form-item>
				
				<Form-item>
					<Row>
				        <Col span="12">
				        		<Button type="primary" 
				        			@click="handleSubmit('form')" 
				        			:loading="isShowLoading"
				        			long size="large">提交</Button>
				        </Col>
				        <Col span="12">
				        		<Button type="ghost" 
				        			@click="handleReset('form')" 
				        			style="margin-left: 20px"
				        			:disabled="isShowLoading"
				        			long size="large">重置</Button>
				        </Col>
				    </Row>
		        </Form-item>
			</Form>
		</div>
		<Spin fix size="large" v-if="isPageLoading">
            <Icon type="load-c" size=18 class="spin-icon-load"></Icon>
            <div>加载中...</div>
        </Spin>
	</div>
</template>

<script>
	import { formatDate } from '@/libs/date-util.js';
	
	import AdService from '@/services/AdService.js';
	import UserService from '@/services/UserService.js';
	import QiniuService from '@/services/QiniuService.js';
	import CImagePicker from '@/components/CImagePicker.vue';
	import CUserFilterItem from '@/components/CUserFilterItem.vue';
	import AppConfig from '@/constants/AppConfig.js';
	

	var $app_config = AppConfig();
	var $adService = AdService();
	var $userService = UserService();
	var $qiniuService = QiniuService();
	
	const $data = {
		isShowLoading: false,
		isPageLoading: false,
		isSearchUserLoading: false,
		imgProgress: 0,
		params: {
			aid: null,
			title: null,
			type: 1,
			webUrl: null,
			userId: null,
			img: {
				url: null,
				key: null,
				width: 0,
				height: 0,
				rate: 3,
				display: {
					width: 450,
					height: 150
				}
			},
			startTime: null,
			endTime: null,
			status: 0
		},
		initData: {
			types: [{
				tid: 1,
				value: '商业广告'
			}, {
				tid: 2,
				value: '影人广告'
			}, {
				tid: 3,
				value: '新闻广告'
			}],
			status: [{
				id: 0,
				value: '未发布'
			}, {
				id: 1,
				value: '发布'
			}]
		},
		users:[],//关联影人
		rules: {
			title: [
                { required: true, type: 'string', message: '广告标题不能为空', trigger: 'blur' }
            ],
            type: [
                { required: true, type: 'integer', message: '广告类型不能为空', trigger: 'change' }
            ],
            status: [
                { required: true, type: 'integer', message: '发布状态不能为空', trigger: 'change' }
            ],
            startTime: [
                { required: true, type: 'date', message: '开始日期不能为空', trigger: 'change' }
            ],
            endTime: [
                { required: true, type: 'date', message: '结束日期不能为空', trigger: 'blur' },
                { required: true, type: 'date', message: '结束日期不能为空', trigger: 'change' }
            ]
        }
	}
	
	export default {
		data() {
			return $data;
		},
		components: {
			CImagePicker, CUserFilterItem
		},
		created() {
		},
		mounted() {
			var $this = this;
			var aid = $this.$route.query.aid;
			$data.params.aid = aid;
			if($data.params.aid != null) {
				$data.isPageLoading = true;
				$adService.getAd(aid)
				.then(function(response) {
					var res = response.data;
					var code = res.rescode;
					if(code == 100) {
						var data = res.data;
						$this.params.title = data.title;
						$this.params.type = data.type;
						if(data.type == 1 || data.type == 3) {
							$this.params.webUrl = data.data;
						} else {//影人广告
							$this.users.push(data.user);
							setTimeout(function() {
								$this.params.userId = data.user.uid;
								$this.$refs.userSelect.setQuery(data.user.name);
							}, 200)
						}
						// start time
						var sdate = new Date(data.startTime);
						$this.params.startTime = sdate;
						// end time
						var edate = new Date(data.endTime);
						$this.params.endTime = edate;
						
						$this.params.status = data.status;
						var imgJson = JSON.parse(data.img);
						$this.params.img = {
							url: imgJson.url,
							key: null,
							width: imgJson.width,
							height: imgJson.height,
							rate: 3,
							display: {
								width: 450,
								height: 150
							}
						}
					}
					$data.isPageLoading = false;
				}, function(error) {
					$data.isPageLoading = false;
				});
			}
		},
		methods: {
			searchUser(query) {//搜索用户
				var $this = this;
				$this.users = [];
				if(query != '' && !$this.isSearchUserLoading) {
					$this.isSearchUserLoading = true;
					$userService.getUsers2Ad(query)
					.then(function(response) {
						var res = response.data;
						var code = res.rescode;
						if(code == 100) {
							var users = res.data;
							$this.users = users;
						}
						$this.isSearchUserLoading = false;
					}, function(error) {
						$this.isSearchUserLoading = false;
					});
				}
			},
			uploadImg(data) {//上传图片
				var $this = this;
				$qiniuService.uploadBase642QiniuServer(data, function() {
				}, function(e) {
					if (e.lengthComputable) {//进度信息是否可用
						$this.posterProgress = e.loaded / e.total * 100;
					}
				})
				.then(function(response) {
					if(response.state == 1) {//成功
						$this.posterProgress = 100;
						self.deployTimeOutId = setTimeout(() => {
							$this.posterProgress = 0;
                        }, 500);		
                        var data = JSON.parse(response.data);
                        $this.params.img.url = $app_config.QiNiu.imageServer + data.key,
                    		$this.params.img.key = data.key,
                    		$this.params.img.width = data.imgW,
                    		$this.params.img.height = data.imgH
					}
				}, function(error) {
					$this.$Message.error(error);
				});
			},
			handleSubmit (name) {
				var $this = this;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                    		$this.isShowLoading = true;
                    		var t = $this.params;
                    		var img = {
                    			width: t.img.width,
                    			height: t.img.height,
                    			url: t.img.url
                    		}
                    		//参数
                    		var data = t.type == 2?t.userId : t.webUrl;
                    		var params = {
                    			aid: t.aid,
                    			title: t.title,
							type: t.type, 
							img	: JSON.stringify(img),
							data: data, 
							startTime: formatDate(t.startTime, "yyyy-MM-dd hh:mm:ss"),
							endTime: formatDate(t.endTime, "yyyy-MM-dd hh:mm:ss"),
							status: t.status
                    		};
                    		console.log(params);
                    		// submit data to server
                    		$adService.edit(params)
                    		.then(function(response) {
                    			var res = response.data;
							var code = res.rescode;
							var msg = res.msg;
							if(code == 100) {
								var data = res.data;
								$this.$router.push({name: 'adList'});
								$this.$Message.success(msg);
							} else {
								$this.$Message.error(msg);
							}
                    			$data.isShowLoading = false;
                    		}, function(error) {
                    			console.log(error);
                    			$data.isShowLoading = false;
                    		});
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            }
		}
	}
</script>

<style scoped="scoped">
	.form {
		width: 50%;
		padding: 30px 50px;
		min-width: 500px;
	}
	
	.r-date, .duration {
		padding: 0px 8px;
		font-size: 14px;
	}
	
	.boxOffice-item {
		align-items: center;
		-webkit-align-items: center;
		-moz-align-items: center;
		display: flex;
		display: -webkit-flex;
		display: -moz-flex;
	}
	@keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
    .spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>